"""提供内容相关功能的模块."""
from fastapi import Request
from sqlalchemy import func, select

from core.database import db_session
from core.exception import AlertException
from core.models import Content
from service import BaseService


class ContentService(BaseService):
# """
# 提供内容相关服务的相关性注入类。
# """

    def __init__(self, request: Request, db: db_session):
        self.request = request
        self.db = db

    def raise_exception(self, status_code: int = 400, detail: str = None, url: str = None):
        raise AlertException(detail, status_code, url)

    def fetch_total_records(self) -> int:
        """
        Lup内容中的全部记录数.
        """
        return self.db.scalar(select(func.count(Content.co_id)))

    def fetch_content(self, co_id: str):
        """
        内容 1我们在数据库中查找枪.
        """
        return self.db.get(Content, co_id)

    def fetch_contents(self, offset: int, per_page: int):
        """
        在数据库中查找内容列表.
        """
        return self.db.scalars(
            select(Content).offset(offset).limit(per_page)
        ).all()

    def read_content(self, co_id: str):
        """
        我们带来了内容.
        """
        content = self.fetch_content(co_id)
        if not content:
            self.raise_exception(404, f"{co_id} : 内容理念不存在.")
        return content

    def read_contents(self, offset: int, per_page: int):
        """
        我们调出内容列表.
        """
        return self.fetch_contents(offset, per_page)
